package com.weichai.app.page.login.viewmodel;

import static com.weichai.app.page.common.PrivacyFragment.KEY_PRIVACY_TYPE;
import static com.weichai.app.page.login.view.BindPhoneFragment.WX_AVATAR;
import static com.weichai.app.page.login.view.BindPhoneFragment.WX_NICK;
import static com.weichai.app.page.login.view.BindPhoneFragment.WX_OPENID;
import static com.weichai.app.page.login.view.BindPhoneFragment.WX_UNION;
import static com.weichai.app.page.login.view.BindPhoneFragment.WX_USER_CODE;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import androidx.databinding.ObservableField;

import com.weichai.app.R;
import com.weichai.app.arch.base.BaseViewModel;
import com.weichai.app.arch.http.ApiException;
import com.weichai.app.arch.http.ApiManager;
import com.weichai.app.arch.http.ApiServer;
import com.weichai.app.arch.http.ApiSubscriber;
import com.weichai.app.arch.http.ApiTransformer;
import com.weichai.app.bean.BaseResult;
import com.weichai.app.bean.UserInfo;
import com.weichai.app.page.mine.UserCenterVM;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import dev.utils.common.validator.ValiToPhoneUtils;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.functions.Predicate;

public class RegisterVM extends BaseViewModel {
    public ObservableField<String> textPhone = new ObservableField<>();//手机号
    public ObservableField<String> textAuthCode = new ObservableField<>();//验证码
    public ObservableField<String> textPsw = new ObservableField<>();//手机密码
    public ObservableField<String> textPswCon = new ObservableField<>();//手机密码确认
    public ObservableField<String> textAuthBtn = new ObservableField<>("获取验证码");//获取验证按钮
    public ObservableField<Boolean> enableAuthBtn = new ObservableField<>(true);//是否可用获取验证码按钮
    public ObservableField<Boolean> enableCommitBtn = new ObservableField<>(false);//是否可用提交按钮
    public ObservableField<Boolean> checkPrivacy = new ObservableField<>(true);//
    public ObservableField<Integer> phoneErrVisible = new ObservableField<>(View.GONE);//
    public ObservableField<Boolean> isShowPwd = new ObservableField<>(false);//密码是否可见
    public ObservableField<Boolean> isShowCon = new ObservableField<>(false);//确认密码是否可见


    /**
     * 提交用户注册
     */
    public void commit() {
        if (!checkPrivacy.get()) {
            showToast("请同意用户隐私协议");
            return;
        }

        if (!checkPwd()) {
            showToast("密码6-20位由数字和字母组成");
            return;
        }

        if (!textPsw.get().equals(textPswCon.get())) {
            showToast("两次密码不一致");
            return;
        }

        HashMap<String, String> params = new HashMap<>();
        params.put("userName", textPhone.get());
        params.put("verificationCode", textAuthCode.get());
        params.put("password", textPsw.get());
        params.put("affirmPassword", textPswCon.get());

        ApiManager
                .getInstance()
                .userRegister(params)
                .compose(new ApiTransformer<>())
                .subscribeWith(new ApiSubscriber<UserInfo>(true, true, this) {
                    @Override
                    public void onSuccess(BaseResult<UserInfo> result) {
                        navigate(R.id.register_to_main_page);
                        getViewModelOfApp(UserCenterVM.class).updateUserInfo(result.data);
                        showToast("登录成功");

                    }
                });
    }


    /**
     * 获取验证码
     */
    public void getPhoneCode() {
        if (TextUtils.isEmpty(textPhone.get())) {
            showToast("请填写手机号");
            return;
        }
        ApiManager
                .getInstance()
                .sendVerify(textPhone.get(), "1")
                .compose(new ApiTransformer<>())
                .subscribeWith(new ApiSubscriber<String>(true, true, this) {
                    @Override
                    public void onSuccess(BaseResult<String> result) {
                        showToast("发送成功");
                        intervalAuthCode();
                    }
                });
    }

    /**
     * 验证码倒计时
     */
    private void intervalAuthCode() {
        Observable
                .interval(1, 1, TimeUnit.SECONDS)
                .take(61)
                .subscribe(value -> {
                    int time = (int) (60 - value);
                    if (time == 0) {
                        textAuthBtn.set(String.format("重新获取验证码", time));
                        enableAuthBtn.set(true);
                    } else {
                        textAuthBtn.set(String.format("%sS后重新获取", time));
                        enableAuthBtn.set(false);
                    }
                });
    }


    //文字变化监听
    public void onTextChanged(CharSequence value, int i, int i1, int i2) {
        ///延迟获取最新输入值
        Observable.just(1)
                .delay(50, TimeUnit.MILLISECONDS)
                .subscribe(integer -> {
                    if (!TextUtils.isEmpty(textPhone.get()) && !ValiToPhoneUtils.isPhoneCheck(textPhone.get())) {
                        phoneErrVisible.set(View.VISIBLE);
                    } else {
                        phoneErrVisible.set(View.GONE);
                    }
                    enableCommitBtn.set(checkCommit());
                });
    }


    //检测密码是否正确
    private boolean checkPwd() {
        return (!TextUtils.isEmpty(textPsw.get()) && Pattern.matches("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$", textPsw.get()));
    }

    /**
     * 检查是否可以提交注册
     *
     * @return 是/否
     */
    public boolean checkCommit() {

        if (!ValiToPhoneUtils.isPhoneCheck(textPhone.get())) {
            return false;
        }
        if (TextUtils.isEmpty(textAuthCode.get())) {
            return false;
        }
        if (TextUtils.isEmpty(textPsw.get())) {
            return false;
        }
        if (TextUtils.isEmpty(textPswCon.get())) {
            return false;
        }
        return true;
    }

    public void showPwd() {
        isShowPwd.set(!isShowPwd.get());
    }

    public void showPwdCon() {
        isShowCon.set(!isShowCon.get());
    }

    public void navPrivacyPage(int type) {
        Bundle param = new Bundle();
        param.putString(KEY_PRIVACY_TYPE, String.valueOf(type));
        navigate(R.id.privacy_page, param);
    }
}